
import {getArticleList,getTeacherList,getBannerList} from '../../api/index'
Page({
  data: {
    articleList: [],//文章列表数据
    pageNo: 1,
    pageSize: 10,
    total: 0,
    loading: false,
    teacherList: [], //咨询师列表
    bannerList: [], // 轮播图列表
    currentSwiper: 0, // 当前轮播图索引
  },
  onLoad(options) {
    this.loadArticleList();
    this.loadTeacherList();
    this.loadBannerList(); // 加载轮播图数据
  },
  onShow() {
    // 页面显示时刷新数据
    this.loadTeacherList()
  },

  // 加载轮播图数据
  async loadBannerList() {
    try {
      console.log('🚀 开始加载轮播图数据...')
      const result = await getBannerList(1, 10)
      console.log('🎠 轮播图接口返回:', result)
      
      // 修复判断逻辑
      if (result && result.list && Array.isArray(result.list)) {
        // 过滤状态正常的轮播图并按排序字段排序
        const bannerData = result.list
          .filter(item => item.status === 0) // 状态为0表示正常
          .sort((a, b) => (a.sort || 0) - (b.sort || 0)) // 按sort字段排序
        
        console.log('✅ 处理后的轮播图数据:', bannerData)
        console.log('📷 轮播图coverImage:', bannerData.map(item => item.coverImage))
        
        this.setData({
          bannerList: bannerData
        })
      } else {
        console.warn('❌ 轮播图数据格式异常:', result)
        this.setData({
          bannerList: []
        })
      }
    } catch (error) {
      console.error('💥 加载轮播图失败:', error)
      this.setData({
        bannerList: []
      })
    }
  },

  // 轮播图切换事件
  swiperChange: function(e) {
    this.setData({
      currentSwiper: e.detail.current
    })
  },

  // 点击轮播图事件
  onBannerTap: function(e) {
    const index = e.currentTarget.dataset.index
    const banner = this.data.bannerList[index]
    
    if (banner && banner.linkUrl) {
      if (banner.type === 2) {
        // 内链 - 跳转到小程序页面
        wx.navigateTo({
          url: banner.linkUrl
        })
      } else if (banner.type === 1) {
        // 外链 - 跳转到webview或复制链接
        this.handleExternalLink(banner.linkUrl)
      }
    }
  },

  // 加载咨询师列表
  async loadTeacherList() {
    this.setData({ loading: true })
    try {
      const result = await getTeacherList(1, 10)

      // 根据新的接口数据结构处理
      let teacherData = []
      
      if (result && result.data && result.data.list && Array.isArray(result.data.list)) {
        teacherData = result.data.list
      } else if (result && Array.isArray(result)) {
        teacherData = result
      } else if (result && result.list && Array.isArray(result.list)) {
        teacherData = result.list
      } else {
        teacherData = []
      }
      console.log('🎯 处理后的咨询师数据:', teacherData)
    // 预处理标签数据
    const processedTeacherData = teacherData.map(teacher => {
      let tags = []
      if (teacher.specialty && typeof teacher.specialty === 'string') {
        tags = teacher.specialty.split(',').map(tag => tag.trim()).filter(tag => tag !== '')
      }
      
      if (tags.length === 0) {
        tags = ['专业咨询']
      }
      
      return {
        ...teacher,
        tags: tags.slice(0, 3) // 最多显示3个标签
      }
    })

    console.log('🏷️ 处理后的咨询师数据:', processedTeacherData)
    
    this.setData({
      teacherList: processedTeacherData
    })
    } catch (error) {
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },
  // 加载文章列表
  async loadArticleList() {
    if(this.data.loading) {
      return 
    }
    wx.showLoading({
      title: '加载中..',
    })
    this.setData({ loading: true })
    try {
      const result = await getArticleList(this.data.pageNo,this.data.pageSize)
      this.setData({
        articleList: this.data.pageNo === 1 ? result.list : this.data.articleList.concat(result.list),
        total: result.total
      })
    } catch (error) {
      console.log("加载文章失败",error);
    } finally {
      this.setData({loading: false})
      wx.hideLoading()
    }
  },
  // 跳转文章详情
  gotoIndexDetail:function(data) {
    let id = data.currentTarget.dataset.id;
    if (id) {
      wx.navigateTo({
        url: `/pages/indexdetail/indexdetail?id=${id}`,
      })
    } else {
      console.error('未获取到课程ID');
    }
  },
  // 跳转心理测评页面
  gotoTest:function() {
    wx.switchTab({
      url: '/pages/test/test',
    })
  },
  // 跳转健康中心介绍页面
  gotoIntroduce:function() {
    wx.navigateTo({
      url: '/pages/introduce/introduce',
    })
  },
  // 跳转文章更多页面
  gotoArticlemore:function() {
    wx.navigateTo({
      url: '/pages/articlemore/articlemore',
    })
  },
  // 跳转咨询师详情
  gotoTeacherdetail(e) {
    const id = e.currentTarget.dataset.id
    if (id) {
      wx.navigateTo({
        url: `/pages/teacherdetail/teacherdetail?id=${id}`
      })
    }
  },
  // 跳转到搜索页面
  gotoSearch:function() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  }
  

})
